<template>
  <table-page
    ref="tablePageRef"
    title="链接管理"
    :search-config="searchConfig"
    :columns="tableConfig"
    :data="processedTableData"
    :loading="loading"
    :pagination-config="paginationConfig"
    :form-config="formConfig"
    :operate-config="operateConfig"
    :default-form-data="getDefaultFormData()"
    @search="handleSearch"
    @reset="handleReset"
    @selection-change="handleSelectionChange"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    @add="handleAdd"
    @edit="handleEdit"
    @delete="handleDelete"
    @batch-delete="handleBatchDelete"
  />
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import TablePage from '@/components/TablePage/index.vue'
import { searchConfig, tableConfig, operateConfig } from './config/pageConfig'
import { formConfig, getDefaultFormData } from './config/formConfig'
import { linksApi } from '@/api/links'

// 状态定义
const tablePageRef = ref(null)
const loading = ref(false)
const tableData = ref([])
const searchParams = ref({})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 分页配置
const paginationConfig = computed(() => ({
  total: pagination.total,
  currentPage: pagination.currentPage,
  pageSize: pagination.pageSize,
  pageSizes: [10, 20, 30, 50],
}))

// 获取友链列表
const fetchLinksList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchParams.value,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
    }
    const res = await linksApi.getList(params)
    tableData.value = res.records
    pagination.total = res.total
  } catch (error) {
    console.error('获取友链列表失败:', error)
    ElMessage.error('获取友链列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = (params) => {
  searchParams.value = params
  pagination.currentPage = 1
  fetchLinksList()
}

// 重置处理
const handleReset = () => {
  searchParams.value = {}
  pagination.currentPage = 1
  fetchLinksList()
}

// 选择行变化
const handleSelectionChange = (rows) => {
  console.log('选中行：', rows)
}

// 每页条数变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchLinksList()
}

// 页码变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchLinksList()
}

// 处理提交数据，格式化技术栈等字段
const formatSubmitData = (data) => {
  const formatted = { ...data }

  // 将技术栈数组转换为字符串（如果后端需要）
  if (Array.isArray(formatted.techStack)) {
    formatted.techStack = formatted.techStack.join(',')
  }

  // 移除临时字段
  delete formatted._techStackInput

  return formatted
}

// 新增链接
const handleAdd = async (data) => {
  try {
    loading.value = true
    const formattedData = formatSubmitData(data)
    await linksApi.addLinks(formattedData)
    ElMessage.success('新增成功')
    fetchLinksList()
  } catch (error) {
    console.error('新增链接失败:', error)
    ElMessage.error('新增链接失败')
  } finally {
    loading.value = false
  }
}

// 编辑链接
const handleEdit = async (data) => {
  try {
    loading.value = true
    const formattedData = formatSubmitData(data)
    await linksApi.updateLinks(formattedData)
    ElMessage.success('保存成功')
    fetchLinksList()
  } catch (error) {
    console.error('编辑链接失败:', error)
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 删除链接
const handleDelete = async (row) => {
  try {
    loading.value = true
    await linksApi.deleteLinks([row.id])
    ElMessage.success('删除成功')
    fetchLinksList()
  } catch (error) {
    console.error('删除链接失败:', error)
    ElMessage.error('删除失败')
  } finally {
    loading.value = false
  }
}

// 批量删除
const handleBatchDelete = async (rows) => {
  try {
    loading.value = true
    const ids = rows.map((row) => row.id)
    await linksApi.deleteLinks(ids)
    ElMessage.success('删除成功')
    fetchLinksList()
    tablePageRef.value?.clearSelection()
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('批量删除失败')
  } finally {
    loading.value = false
  }
}

// 处理上移下移
const handleMoveUp = async (row) => {
  const index = tableData.value.findIndex((item) => item.id === row.id)
  if (index <= 0) return

  try {
    loading.value = true
    const newData = JSON.parse(JSON.stringify(tableData.value))

    const currentOrder = newData[index].orderNum
    const targetOrder = newData[index - 1].orderNum

    // 如果当前序号已经是0，则不允许上移
    if (currentOrder === 0) return

    if (currentOrder === targetOrder) {
      // 序号相同时，减小当前序号，但不能小于0
      const newOrder = Math.max(currentOrder - 1, 0)
      await linksApi.updateOrder(newData[index].id, newOrder)
    } else {
      // 序号不同时，交换序号
      await linksApi.updateOrder(newData[index].id, targetOrder)
      await linksApi.updateOrder(newData[index - 1].id, currentOrder)
    }

    // 刷新列表
    await fetchLinksList()
    ElMessage.success('移动成功')
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleMoveDown = async (row) => {
  const index = tableData.value.findIndex((item) => item.id === row.id)
  if (index >= tableData.value.length - 1) return

  try {
    loading.value = true
    const newData = JSON.parse(JSON.stringify(tableData.value))

    const currentOrder = newData[index].orderNum
    const targetOrder = newData[index + 1].orderNum

    if (currentOrder === targetOrder) {
      // 序号相同时，增加当前序号
      await linksApi.updateOrder(newData[index].id, currentOrder + 1)
    } else {
      // 序号不同时，交换序号
      await linksApi.updateOrder(newData[index].id, targetOrder)
      await linksApi.updateOrder(newData[index + 1].id, currentOrder)
    }

    // 刷新列表
    await fetchLinksList()
    ElMessage.success('移动成功')
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 为每一行数据添加排序方法和按钮状态
const processedTableData = computed(() => {
  return tableData.value.map((item) => ({
    ...item,
    onMoveUp: handleMoveUp,
    onMoveDown: handleMoveDown,
    upDisabled: item.orderNum === 0, // 添加上移按钮禁用状态
  }))
})

// 页面加载时获取数据
onMounted(() => {
  fetchLinksList()
})
</script>

<style lang="scss" scoped>
// 导入主题变量和混合器
@use '@/assets/styles/theme/base.scss' as *;
@use '@/assets/styles/mixins.scss' as *;

:deep(.number-input) {
  width: 100%;

  // 隐藏上下调节按钮
  &::-webkit-inner-spin-button,
  &::-webkit-outer-spin-button {
    -webkit-appearance: none;
    appearance: none;
    margin: 0;
  }

  /* Firefox */
  -moz-appearance: textfield;
  appearance: textfield;
}

:deep(.el-button) {
  &:hover {
    .el-icon {
      transform: scale(1.2);
    }
  }

  .el-icon {
    transition: transform 0.2s;
  }
}

// 图标上传样式
:deep(.icon-upload) {
  .icon-uploader {
    .el-upload {
      width: 80px;
      height: 80px;
      border: 1px dashed var(--el-border-color);
      border-radius: 8px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      background-color: var(--el-fill-color-lighter);

      &:hover {
        border-color: var(--el-color-primary);
        background-color: var(--el-fill-color-light);

        .upload-icon {
          color: var(--el-color-primary);
        }
      }

      .el-image {
        display: block;
        width: 100%;
        height: 100%;

        &::after {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.3);
          opacity: 0;
          transition: opacity 0.2s;
        }

        &:hover::after {
          opacity: 1;
        }
      }
    }
  }

  .icon {
    width: 80px;
    height: 80px;
    object-fit: cover;
    display: block;
  }

  .upload-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: var(--el-text-color-secondary);
    font-size: 12px;
  }

  .upload-icon {
    font-size: 24px;
    margin-bottom: 4px;
  }

  .el-upload__tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 8px;
    line-height: 1.5;
  }
}

// 封面图上传样式
:deep(.cover-upload) {
  .cover-uploader {
    .el-upload {
      width: 200px;
      height: 120px;
      border: 1px dashed var(--el-border-color);
      border-radius: 8px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      background-color: var(--el-fill-color-lighter);

      &:hover {
        border-color: var(--el-color-primary);
        background-color: var(--el-fill-color-light);

        .upload-icon {
          color: var(--el-color-primary);
        }
      }

      .el-image {
        display: block;
        width: 100%;
        height: 100%;

        &::after {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.3);
          opacity: 0;
          transition: opacity 0.2s;
        }

        &:hover::after {
          opacity: 1;
        }
      }
    }
  }

  .cover-image {
    width: 200px;
    height: 120px;
    object-fit: cover;
    display: block;
  }

  .cover-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: var(--el-text-color-secondary);
    font-size: 13px;
  }

  .upload-icon {
    font-size: 28px;
    margin-bottom: 6px;
  }

  .el-upload__tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 8px;
    line-height: 1.5;
  }
}

// 技术栈标签输入样式 - 重新设计
:deep(.tech-stack-container) {
  width: 100%;

  // 输入框包装器
  .tech-stack-input-wrapper {
    width: 100%;
    margin-bottom: 12px;

    .el-input {
      width: 100%;
    }
  }

  // 标签容器
  .tech-stack-tags-container {
    width: 100%;
    margin-top: 0;
  }

  // 标签展示区域
  .tech-stack-tags {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
    padding: 12px;
    background: linear-gradient(
      135deg,
      var(--el-fill-color-lighter) 0%,
      var(--el-fill-color-light) 100%
    );
    border-radius: 8px;
    border: 1px solid var(--el-border-color-lighter);
    min-height: 52px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

    .el-tag {
      margin: 0;
      @include transition(all);
      font-size: 13px;
      font-weight: 500;
      padding: 6px 14px;
      height: auto;
      line-height: 1.6;
      border-radius: 6px;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 3px 8px rgba(0, 0, 0, 0.12);
      }

      .el-tag__close {
        margin-left: 8px;
        font-size: 14px;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background-color: rgba(255, 255, 255, 0.3);
        @include transition(all);

        &:hover {
          background-color: rgba(255, 255, 255, 0.5);
          transform: scale(1.1);
        }
      }
    }
  }

  // 空状态提示
  .tech-stack-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16px;
    color: var(--el-text-color-placeholder);
    font-size: 13px;
    background: linear-gradient(
      135deg,
      var(--el-fill-color-lighter) 0%,
      var(--el-fill-color-light) 100%
    );
    border-radius: 8px;
    border: 1px dashed var(--el-border-color-lighter);
    min-height: 52px;
  }
}

// 表单整体样式优化
:deep(.drawer-form) {
  .el-form-item {
    margin-bottom: 24px;

    .el-form-item__label {
      font-weight: 500;
      color: var(--el-text-color-regular);
    }

    .el-textarea {
      .el-textarea__inner {
        resize: vertical;
        min-height: 80px;
      }
    }
  }
}
</style>
